package com.huadao.cart_ccs.netty;

import com.huadao.cart_ccs.Event.ConsoleEvent;
import com.huadao.cart_ccs.common.ByteUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class ConsolHandler extends LoggingHandler {

    public ConsolHandler(LogLevel level) {
        super(level);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (logger.isEnabled(internalLevel)) {
            logger.log(internalLevel, format(ctx, "READ", msg));

            if(msg instanceof ByteBuf){
                byte[] response=((ByteBuf) msg).array();
                String string= ByteUtils.getHexByte(response,0,((ByteBuf) msg).readableBytes());
                EventBus.getDefault().post(new ConsoleEvent(string,ConsoleEvent.TYPE_RESPONSE,new Date()));
            }
        }
        ctx.fireChannelRead(msg);
    }
}
